package org.suze.springboot.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @Date : 下午3:53 2017/9/11
 * @Author : 石冬冬-Heil Hitler(dongdong.shi@mljr.com)
 */
@Component(value = "redisGeneral")
public class RedisGeneral {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisGeneral.class);

    private final String KEY = "2";
    private final int DEFAULT_INC_LENG = 6;
    private final long EXPIRE = 2*24*60*60*1000;

    @Resource(name = "valueOperations")
    private ValueOperations<String,String> valueOperations;

    public String general(String prefix){
        return this.general(prefix,DEFAULT_INC_LENG);
    }

    /**
     * 生成编号
     * @param prefix
     * @return
     */
    public String general(String prefix,int incLength){
        StringBuffer code = new StringBuffer();
        try {
            String find = valueOperations.get(KEY);
            if(null == find){
                valueOperations.set(KEY,String.valueOf(0),EXPIRE, TimeUnit.MILLISECONDS);
            }
            Long increment = valueOperations.increment(KEY,1);
            code.append(prefix).append(DateUtil.formate(new Date()));
            int len = String.valueOf(increment).length();
            // 不足位数补零
            for (int i = len; i < incLength; i++) {
                code.append(0);
            }
            // 添加顺序数
            code.append(increment);
        } catch (Exception e) {
            LOGGER.error("general code focus an exception,",e);
        }
        return code.toString();
    }


    public static class DateUtil {

        private static final String DATE_FORMAT = "yyyyMMdd";

        @SuppressWarnings("rawtypes")
        private static ThreadLocal threadLocal = new ThreadLocal() {
            protected synchronized Object initialValue() {
                return new SimpleDateFormat(DATE_FORMAT);
            }
        };

        public static SimpleDateFormat getDateFormat() {
            return (SimpleDateFormat) threadLocal.get();
        }

        public static Date parse(String textDate) throws ParseException {
            return getDateFormat().parse(textDate);
        }


        public static String formate(Date date){
            return getDateFormat().format(date);
        }

    }
}
